from flask import Blueprint, render_template, request, jsonify, make_response, g
from common.libs.Helper import ops_render  # 统一渲染方法
import json
from common.libs.UrlManager import UrlManager
from common.libs.user.UserService import UserService
from werkzeug.utils import redirect

from common.models.User import User
from common.libs.user.UserService import UserService
from application import app, db
route_user = Blueprint("user_page ", __name__)


@route_user.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'GET':
        return ops_render('user/login.html')

    resp = {"code": 200, 'msg': "登录成功", "data": {}}
    req = request.values
    print('req==========', req)
    login_name = req["login_name"] if "login_name" in req else ''
    login_pwd = req["login_pwd"] if "login_pwd" in req else ''

    # 检查用户名是否为空
    if login_name is None or len(login_name) < 1:
        resp["code"] = -1
        resp["msg"] = '请输入正确的登录用户名'
        return jsonify(resp)

    # 检查密码是否为空
    if login_pwd is None or len(login_pwd) < 1:
        resp["code"] = -1
        resp["msg"] = '请输入正确的登录用户名'
        return jsonify(resp)

    # 检查数据库中是否存在用户

    user_info = User.query.filter_by(login_name=login_name).first()
    print("user_info =======", user_info,type(user_info))
    if not user_info:
        resp['code'] = -1
        resp['msg'] = "请输入正确的登录用户名和密码"
        return jsonify(resp)

    # 用户输入的密码和产生随机字符串+密码对比
    if user_info.login_pwd != UserService.genePwd(login_pwd, user_info.login_salt):
        resp['code'] = -1
        resp["msg"] = '请输入正确的登录用户名和密码'
        return jsonify(resp)
    # 设置cookies
    response = make_response(json.dumps(resp))
    response.set_cookie(app.config["AUTH_COOKIE_NAME"], "%s#%s" % (UserService.geneAuthCode(user_info), user_info.uid))

    # response.set_cookie( app.config['AUTH_COOKIE_NAME'], '%s#%s' % (UserService.geneAuthCode(user_info), user_info.uid),60 * 60 * 24 * 120)  # 保存120天
    # return response
    return response

# 登出
@route_user.route('/logout')
def logout():
    response = make_response(redirect(UrlManager.buildUrl("/user/login")))
    response.delete_cookie(app.config["AUTH_COOKIE_NAME"])
    return response


@route_user.route('/edit', methods=['POST', 'GET'])
def edit():
    if request.method == "GET":
        return ops_render('user/edit.html')
    else:
        # 获取请求值
        req = request.values
        nickname = req["nickname"] if "nickname" in req else ""
        email = req["email"] if "email" in req else ""

        # 统一的回调值
        resp = {'code': 200, "msg": "操作成功", "data": {}}
        # 判断
        if nickname is None or len(nickname)<1:
            resp["code"] = -1
            resp["msg"] = "请输入符合规范的姓名"
            return jsonify(resp)

        if email is None or len(email)<1:
            resp["code"] = -1
            resp["msg"] = "请输入符合规范的邮箱"
            return jsonify(resp)


        user_info = g.current_user
        # 更新用户名和邮箱
        user_info.nickname = nickname
        user_info.email = email
        # 更新到数据库中
        db.session.add(user_info)
        db.session.commit()

        # 返回
        return jsonify(resp)


@route_user.route('/reset-pwd', methods=['POST', 'GET'])
def reset():
    if request.method == "GET":
        return ops_render('user/reset_pwd.html')
    else:
        resp = {'code': 200, "msg": '操作成功', 'data': {}}
        req = request.values

        old_password = req["old_password"] if "old_password" in req else ""
        new_password = req["new_password"] if "new_password" in req else ""

        if old_password is None or len(old_password) < 6:
            resp["code"] = -1
            resp["msg"] = "请输入符合规范的原密码"
            return jsonify(resp)

        if new_password is None or len(new_password) < 6:
            resp["code"] = -1
            resp["msg"] = "请输入符合规范的新密码"
            return jsonify(resp)

        if old_password == new_password:
            resp["code"] = -1
            resp["msg"] = "请重新输入，原名密码和新密码一致"
            return jsonify(resp)

        user_info = g.current_user

        user_info.login_pwd = UserService.genePwd(new_password, user_info.login_salt)
        db.session.add(user_info)
        db.session.commit()

        response = make_response(json.dumps(resp))
        response.set_cookie(app.config["AUTH_COOKIE_NAME"],
                            "%s#%s" % (UserService.geneAuthCode(user_info), user_info.uid))

        return jsonify(resp)






